/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cersoft.xmascharity.ejb;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.cersoft.xmascharity.entity.Child;
import com.cersoft.xmascharity.entity.Child_;
import com.cersoft.xmascharity.entity.Family;
import com.cersoft.xmascharity.entity.Image;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Root;

/**
 *
 * @author pbo
 */
@Stateless
public class ChildFacade extends AbstractFacade<Child> {
    @PersistenceContext(unitName = "XmasCharityPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public ChildFacade() {
        super(Child.class);
    }
    
    public List<Child> getChildren(Family f){
        return em.createNamedQuery("findChildren4Family").setParameter("family", f).getResultList();
    }
    
    
    
    public List<Child> getChildrenCriteriaAPI(Family f){
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Child> cq = cb.createQuery(Child.class);
        Root<Child> child = cq.from(Child.class);
//        cq.select(child).where(cb.equal(child.get(Child_.family), f)).orderBy(cb.desc(child.get(Child_.name)));
        cq.select(child).where(cb.equal(child.get("family"), f)).orderBy(cb.desc(child.get("age")));
        TypedQuery<Child> q = em.createQuery(cq);
        return q.getResultList();
    }
    
    
    public void addImage(Child c, Image i) {
        c.getImages().add(i);
        i.setChild(c);
        em.persist(i);
    } 
    
}
